import {
  configureStore,
  createSlice,
  createAsyncThunk,
} from './@reduxjs/toolkit'
import axios from 'axios'


const getTodos = createAsyncThunk(
  'todos', // todos/pending todos/fulfilled todos/rejected
  () => axios.get(`http://localhost:8080/todos/list`)
)

const todosSlice = createSlice({
  name: "todos", // 切片前缀
  initialState: { // 切片的初始状态
    list: [], // 请求的数组
    loading: false, // 是否正在请求
    error: undefined, // 请求是否出错了
  },
  extraReducers: (builder) => {
    builder
      .addCase(getTodos.pending, (state) => {
        state.loading = true
      })
      .addCase(getTodos.fulfilled, (state, action) => {
        console.log('getTodos.fulfilled')
        state.loading = false
        state.list = action.payload.data // 将请求成功的值保存到 state.list 中
        state.error = undefined
      })
      .addCase(getTodos.rejected, (state, action) => {
        state.loading = false
        state.error = action.error
        state.list = []
      })
  },
})

const store = configureStore({
  reducer: todosSlice.reducer
})

const asyncThunk = getTodos()
const promise = store.dispatch(asyncThunk)

const todos = document.getElementById('todos')


promise.then(
  result => {
    console.log(store.getState(todosSlice.reducerPath)) // 数据同时也在仓库的状态中保存着
    console.log(`result `, result)
    if (result.error) {
      todos.innerHTML = `<li>${result.error.message}</li>`
    } else {
      todos.innerHTML = result.payload.data.map(todo => `<li>${todo.text}</li>`).join('')
    }
  },
)

